package tn.talan.xdocreport.generationofreports;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import tn.talan.xdocreport.model.Project;

import fr.opensagres.xdocreport.core.XDocReportException;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import fr.opensagres.xdocreport.template.formatter.FieldsMetadata;

public class GeneratePPTXreport implements GenererDocument {
	public Boolean genrateReport(String nametemplate, String nameoutput,
			Map data) throws IOException, XDocReportException {

		try {
			// 1) Load PPTX file by filling Velocity template engine and cache
			// it to the registry
			String cheminabsoluprojet = new File(".").getAbsolutePath();

			InputStream in = new FileInputStream(cheminabsoluprojet.substring(
					0, cheminabsoluprojet.length() - 1)
					+ "src\\main\\resources\\template\\"
					+ nametemplate
					+ ".pptx");

			IXDocReport report = XDocReportRegistry.getRegistry().loadReport(
					in, TemplateEngineKind.Velocity);
			IContext context;

			FieldsMetadata fieldsMetadata = report.createFieldsMetadata();

			context = report.createContext();
			Iterator iter = data.entrySet().iterator();
			while (iter.hasNext()) {
				Map.Entry ent = (Map.Entry) iter.next();

				String key = (String) ent.getKey();

				Object val = ent.getValue();

				if (val instanceof List)
					fieldsMetadata.load((String) key, ((List) val).get(0)
							.getClass(), true);
				else
					fieldsMetadata.load((String) key, val.getClass());

				context.put((String) key, val);
			}

			// 3) Generate report by merging Java model with the PPTX
			OutputStream out = new FileOutputStream(new File(
					"src/main/resources/files/" + nameoutput + ".pptx"));
			report.process(context, out);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (XDocReportException e) {
			e.printStackTrace();
			return false;
		}

	}

}